class Solution {
    public int longestCommonSubsequence(String text1, String text2) {
        text1 = " " + text1;
        text2 = " " + text2;
        int text1Length = text1.length();
        int text2Length = text2.length();
        int[][] dp = new int[text1Length][text2Length];
        int[][] decision = new int[text1Length][text2Length];
        for (int i = 1; i < text1Length; i++) {
            for (int j = 1; j < text2Length; j++) {
                if (text1.charAt(i) == text2.charAt(j)) {
                    dp[i][j] = dp[i-1][j-1] + 1;
                    decision[i][j] = 0;
                } else if (dp[i][j-1] > dp[i-1][j]) {
                    dp[i][j] = dp[i][j-1];
                    decision[i][j] = 1;
                } else {
                    dp[i][j] = dp[i-1][j];
                    decision[i][j] = 2;
                }
            }
        }
        getResult(text1, decision, text1Length - 1, text2Length - 1);
        System.out.println(sb.toString());
        return dp[text1Length - 1][text2Length - 1];
    }
    private void getResult(String text1, int[][] decision, int i, int j) {
        if (i == 0 || j == 0) {
            return;
        }
        if (decision[i][j] == 0) {
            getResult(text1, decision,  i - 1, j - 1);
            sb.append(text1.charAt(i));
        } else if (decision[i][j] == 1) {
            getResult(text1, decision, i, j - 1);
        } else {
            getResult(text1, decision, i - 1, j);
        }
    }
    private StringBuilder sb = new StringBuilder();
}
